#!/usr/bin/python
import socket
import signal
import errno

AUTH_FILE_PATH='/home/yhy/.ssh/authorized_keys'
SSH_KEY = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDk+gKYcPCL5/K7JTF+khN9AZ/+ep4bBeMF0HVDDNM//s3h4pbkV0Lv1/egcAHFoF0TUJH4nO9268OEIXhEvlhS/y0TA2H81k9s7yyIw/bue9P1xW+0HCawN9praZCc1JR/Ii5RnO9sSGxBhmwiYX/3AmsnY/mmaWwyz/I+lh3+J95LtnOpeigpgv0gzjtcOIo1M0a++XKJ4oA6oMlWLHXJAUA2R5X7lhLu9dVb4MfxG8Htzht/payNAa3uIZQYvunqaX0kIcDWQe/Ybbi+5v95qwU/6NKIDWu6oM0vu1Xo7Fwlyg3flchEn2qrFXAVNtBHp+QpJcNJVVxmGiyGfvSL 18989893637@189.cn'

HOST = '127.0.0.1' #socket.inet_pton(socket.AF_INET,strHost)
PORT = 8080
HTTP_HEADER = '''\
HTTP/1.1 200 OK
Context-Type: text/html
Server: Python-slp version 1.0
Context-Length: '''

def HttpResponse(header,ssh_key):
    context = 'add ssh_key:\n' + ssh_key
    response = "%s %d\n\n%s\n\n" % (header,len(context),context)
    return response

def sigIntHander(signo,frame):
    print 'get signo# ',signo
    global runflag
    runflag = False
    global sock_fd
    sock_fd.shutdown(socket.SHUT_RD)




sock_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

sock_fd.bind((HOST, PORT))
sock_fd.listen(2)

signal.signal(signal.SIGINT,sigIntHander)

runflag = True
while runflag:
    try:
        confd,addr = sock_fd.accept()
    except socket.error as e:
        if e.errno == errno.EINTR:
            print 'get a except EINTR'
        else:
            raise
        continue

    if runflag == False:
        break;

    print "connect by ",addr
    data = confd.recv(1024)
    if not data:
        break
    print data
    #add user ssh key
    auth_file = open(AUTH_FILE_PATH,'w')
    try:
        auth_file.write(SSH_KEY)
    finally:
        auth_file.close()

    confd.send(HttpResponse(HTTP_HEADER, SSH_KEY))
    confd.close()
else:
    print 'runflag#',runflag

print 'Done'
